package com.solr.self.index;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;

import com.solr.self.search.SolrServer;

public class SolrjOperationIndex {
	
	private static final int LIMIT = 500;
	 
	String dbURL = "jdbc:mysql://172.19.0.27:9652/test";
//	String dbURL = "jdbc:mysql://172.19.6.4:3306/post_crawl";
    String driver = "com.mysql.jdbc.Driver";
    String username = "dev";
    String password = "";

	public static Connection getConnection(String driverClassName,
			String dbURL, String userName, String password)
			throws ClassNotFoundException, SQLException {
		java.sql.Connection con = null;

		// 加载连接数据库的驱动类
		Class.forName(driverClassName);
		// 用用户名、密码连接数据库
		con = DriverManager.getConnection(dbURL, userName, password);

		return con;
	}
	
	/**
     * <创建或者更新索引>
     * <功能详细描述>
     * @throws Exception [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
	@SuppressWarnings("null")
	public void updateSolrIndex() throws Exception 
    {
		Connection con = getConnection(driver, dbURL, username, password);;
		PreparedStatement psm = null;
//		CommonsHttpSolrServer httpSolrServer = SolrServer.getInstance().getServer();
		CommonsHttpSolrServer httpSolrServer = SolrServer.getServer();
		for (int i = 0; i<10; i++) 
		{
			int start = i * LIMIT;
		
	        String sql = "select id,title,content,author,type from news";
//	        String sql = "select id,name,size,type,domain,description,address,url,tel,contact_name,phone,status from corp";
	        sql = sql + " limit " + start + "," + LIMIT;
        
	        int addCount = 0;
	        Collection<SolrInputDocument> docRecords = new ArrayList<SolrInputDocument>();
	        try {
	            // 判断SQL语句是否为查询语句，以放置修改数据库
	            sql = sql.trim();
	            // 执行查询
	            psm = con.prepareStatement(sql);
				ResultSet rs = psm.executeQuery();
				
				while (rs.next())
				{
					 SolrInputDocument doc = new SolrInputDocument();
					 doc.addField("id", rs.getString("id"));
					 doc.addField("title", rs.getString("title"));
					 doc.addField("content", rs.getString("content"));
					 doc.addField("author", rs.getString("author"));
					 doc.addField("type", rs.getString("type"));
                     //在这里请注意date的格式，要进行适当的转化，上文已提到
//                     doc.addField("id", rs.getString("id"));
//                     doc.addField("corpName", rs.getString("name"));
//                     doc.addField("size", rs.getObject("size"));
//                     doc.addField("type", rs.getString("type"));
//                     doc.addField("domain", rs.getString("domain"));
//                     doc.addField("description", rs.getString("description"));
//                     doc.addField("address", rs.getString("address"));
//                     doc.addField("url", rs.getString("url"));
//                     doc.addField("tel", rs.getString("tel"));
//                     doc.addField("contactName", rs.getString("contact_name"));
//                     doc.addField("phone", rs.getString("phone"));
//                     doc.addField("status", rs.getString("status"));
                     // 将记录加到docRecords中
                     docRecords.add(doc);
					addCount++;
				}
				System.out.print("此次增量索引数量："+ addCount);
	        } catch (Exception e){
	        	throw new RuntimeException(e);
	        }finally{
		        psm.close();
		        psm = null;
	        }
	        try {
	        	if (null != docRecords && docRecords.size()>0) {
		        	UpdateResponse response = httpSolrServer.add(docRecords);
		        	if (response.getStatus() != 0) {  
		        		System.out.println("Some horrible error has occurred, status is: " +  response.getStatus());  
		              }  
		        	docRecords.clear();  
		        	System.out.println("time:"+response.getQTime());
	//	        	httpSolrServer.add(docRecords);
		              //对索引进行优化
	//	        	httpSolrServer.optimize();
		        	httpSolrServer.commit();
	        	}
	       } catch (Exception e) {
	              e.printStackTrace();
	       }
			if(addCount < LIMIT )
			{
				break;
			}
		}
		con.close();
    	con = null;
		System.out.print("Exit CreateIndex.writeIndex()");
    }
	
	/**
	 * <根据文档唯一标示id删除索引记录>
	 * <功能详细描述>
	 * @param ids [参数说明]
	 * 
	 * @return void [返回类型说明]
	 * @exception throws [违例类型] [违例说明]
	 * @see [类、类#方法、类#成员]
	 */
	public void deleteSolrIndexByIds(List<String> ids){
		CommonsHttpSolrServer httpSolrServer = SolrServer.getServer();
		try {
			httpSolrServer.deleteById(ids);
			httpSolrServer.commit();
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * <根据查询条件查询索引记录，如果query为*:*则表示删除所有索引>
	 * <功能详细描述>
	 * @param query [参数说明]
	 * 
	 * @return void [返回类型说明]
	 * @exception throws [违例类型] [违例说明]
	 * @see [类、类#方法、类#成员]
	 */
	public void deleteSolrIndexByQuery(String query){
		CommonsHttpSolrServer httpSolrServer = SolrServer.getServer();
		try {
			httpSolrServer.deleteByQuery(query);
			httpSolrServer.commit();
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	// 测试
	public static void main(String[] args) 
	{
		SolrjOperationIndex ci = new SolrjOperationIndex();
		try {
			long startTime = new Date().getTime();
			ci.updateSolrIndex();
			long endTime = new Date().getTime();
			System.out.println("\n这花费了" + (endTime - startTime) + " 毫秒增加到索引!");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
